package org.diysearch.helpers;

import java.util.List;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.diysearch.dao.interfaces.UserDao;
import org.diysearch.exceptions.UserNotFoundException;
import org.diysearch.models.User;
import org.diysearch.models.UserElement;
import org.diysearch.tools.BaseTool;

public abstract class UserHelper {
	private static final UserDao dao = (UserDao) BaseTool.IOC_ENGINE.getBean("userDao");
	private static Options olist = new Options();
	
	static {
		olist.addOption("l",false,"get links");
		olist.addOption("c",false,"get comments");
		olist.addOption("t",false,"get tags");
	}
	
	public static User login (User u) throws Exception {
		return dao.authenticate(u);
	}
	
	public static void logIp (User u) throws Exception {
		dao.insertUserIp(u);
	}
	public static int save (User user) throws Exception {
		return dao.save(user);
	}
	public static int save(int id,
			String username,
			String password,
			String email,
			int permissions,
			int status,
			int authType,
			String authenticator,
			int rating,
			List<UserElement> elements) throws Exception 
	{
		User u = new User();
		u.setId(id);
		u.setUsername(username);
		u.setPassword(password);
		u.setEmail(email);
		u.setPermissions(permissions);
		u.setStatus(status);
		u.setAuthType(authType);
		u.setAuthenticator(authenticator);
		u.setRating(rating);
		if (elements != null) {
			u.setElements(elements);
		}
		
		return save(u);
	}
	
	public static User getUser(User user, String[] args) throws Exception {
		CommandLineParser parser = new BasicParser();
		CommandLine cmd = parser.parse(olist, args);
		
		User u = null;
		// first just get the base user record
		String check = "";
		if (user.getId() >0) {
			u = dao.findById(user.getId());
			check = "BY ID: " + user.getId();
		} else if (user.getUsername() != null) {
			u = dao.findByUsername(user.getUsername());
			check = "BY USERNAME: " + user.getUsername();
		} else {
			u = dao.findByEmail(user.getEmail());
			check = "BY EMAIL: " + user.getEmail();
		}
		
		if (u == null) {
			throw new UserNotFoundException ("Could not find the user you were looking for: " + check);
		}
		
		if (cmd.hasOption("l")) {
			u.setLinks(LinkHelper.fetchLinks(new String[] {"-usr " + u.getId()}));
		}
		
		if (cmd.hasOption("c")) {
			u.setComments(CommentHelper.getCommentsForUser(u.getId()));
		}
		
		if (cmd.hasOption("t")) {
			u.setTags(TagHelper.getMyTags(u.getId()));
		}
		
		return u;
	}
	
	public static int delete (int uid) throws Exception {
		User u = new  User();
		u.setId(uid);
		return dao.delete(u);
	}
	
	public static User confirm(String token) throws Exception {
		User u = new User();
		u.setToken(token);
		return dao.findByToken(u);
	}
	
}
